package com.sky.controller.admin;

import com.sky.config.Ossconfiguration;
import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Set;
import java.util.UUID;

@RequestMapping("/admin/common")
@Slf4j
@RestController
@Api(tags = "文件上传")
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;
    @ApiOperation(value = "文件上传")
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        try {
            log.info("文件上传，文件名：{}", file.getOriginalFilename());
            // 获取上传文件的原始名称
            String originName = file.getOriginalFilename();
            // 提取文件后缀，用于保持上传后的文件类型不变
            String suffix= originName.substring(originName.lastIndexOf("."));
            // 使用UUID生成唯一名称，以减少文件名冲突的可能性
            String objectName= UUID.randomUUID().toString() + suffix;
            // 调用aliOssUtil的upload方法上传文件，并获取上传后的文件路径
            String filePath  = aliOssUtil.upload(file.getBytes(), objectName);
            return Result.success(filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
